import { defineStore } from 'pinia';
import { parseChapters, cleanText, detectEncodingQuality } from '../utils/textParser';

// 本地存储键名
const STORAGE_KEYS = {
  BOOK_DATA: 'bookReader_bookData',
  VOICE_SETTINGS: 'bookReader_voiceSettings',
  AUTO_PLAY: 'bookReader_autoPlay',
  CURRENT_CHAPTER: 'bookReader_currentChapter'
};

export const useBookStore = defineStore('book', {
  state: () => ({
    bookTitle: '',
    chapters: [] as string[],
    currentChapter: 0,
    isPlaying: false,
    isPaused: false, // 新增：暂停状态
    speech: null as SpeechSynthesisUtterance | null,
    // 语音设置
    voiceSettings: {
      voice: null as SpeechSynthesisVoice | null,
      rate: 1.0,        // 语速 0.1-10
      pitch: 1.0,       // 音调 0-2
      volume: 1.0       // 音量 0-1
    },
    // 自动播放设置
    autoPlay: false,    // 是否自动播放
    autoPlayDelay: 1000 // 章节间延迟时间(毫秒)
  }),
  actions: {
    loadBook(content: string, filename: string) {
      const cleaned = cleanText(content);
      const quality = detectEncodingQuality(cleaned);
      
      // 如果编码质量太差，给出警告
      if (quality < 0.8) {
        console.warn('文本编码质量较低，可能存在乱码:', quality);
      }
      
      this.bookTitle = filename.replace(/.txt$/i, '');
      this.chapters = parseChapters(cleaned);
      this.currentChapter = 0;
      
      // 保存到本地存储
      this.saveToLocalStorage();
    },
    playChapter(index: number) {
      this.currentChapter = index;
      this.isPlaying = true;
      this.isPaused = false;  // 重置暂停状态
      
      if (this.speech) speechSynthesis.cancel();
      
      this.speech = new SpeechSynthesisUtterance(
        this.chapters[index]
      );
      
      // 应用语音设置
      this.speech.lang = 'zh-CN';
      // 只有当voice不为null时才设置
      if (this.voiceSettings.voice && this.voiceSettings.voice.name) {
        console.log('设置语音:', this.voiceSettings.voice.name);
        this.speech.voice = this.voiceSettings.voice;
      } else {
        console.log('使用默认语音');
      }
      this.speech.rate = this.voiceSettings.rate;
      this.speech.pitch = this.voiceSettings.pitch;
      this.speech.volume = this.voiceSettings.volume;
      
      this.speech.onend = () => {
        this.isPlaying = false;
        
        // 如果开启自动播放，自动播放下一章
        if (this.autoPlay && this.currentChapter < this.chapters.length - 1) {
          setTimeout(() => {
            this.playChapter(this.currentChapter + 1);
          }, this.autoPlayDelay);
        }
      };
      
      speechSynthesis.speak(this.speech);
      
      // 保存当前章节到本地存储
      this.saveToLocalStorage();
    },
    stopPlayback() {
      if (this.speech) speechSynthesis.cancel();
      this.isPlaying = false;
      this.isPaused = false;  // 重置暂停状态
    },
    
    // 新增：暂停播放
    pausePlayback() {
      if (this.isPlaying && !this.isPaused) {
        speechSynthesis.pause();
        this.isPaused = true;
      }
    },
    
    // 新增：恢复播放
    resumePlayback() {
      if (this.isPaused) {
        speechSynthesis.resume();
        this.isPaused = false;
      }
    },
    
    // 新增：切换暂停/恢复
    togglePause() {
      if (this.isPaused) {
        this.resumePlayback();
      } else if (this.isPlaying) {
        this.pausePlayback();
      }
    },
    
    // 新增：安全恢复（恢复失败则重新播放当前章节）
    safeResumeOrRestart() {
      if (this.isPaused) {
        try {
          speechSynthesis.resume();
          // 等待浏览器恢复，如果失败则重启播放
          window.setTimeout(() => {
            const speaking = (speechSynthesis as any).speaking as boolean;
            const paused = (speechSynthesis as any).paused as boolean;
            if (!speaking || paused) {
              console.warn('恢复失败，重新播放当前章节');
              this.playChapter(this.currentChapter);
            } else {
              this.isPaused = false;
              this.isPlaying = true;
            }
          }, 100);
        } catch (e) {
          console.warn('resume 调用异常，改为重新播放:', e);
          this.playChapter(this.currentChapter);
        }
      } else if (!this.isPlaying) {
        this.playChapter(this.currentChapter);
      }
    },
    
    // 新增：同步浏览器speech状态到store
    syncSpeechStateFromBrowser() {
      const speaking = (speechSynthesis as any).speaking as boolean;
      const paused = (speechSynthesis as any).paused as boolean;
      if (!speaking) {
        // 浏览器端认为未在说话
        this.isPlaying = false;
        this.isPaused = false;
      } else {
        // 浏览器端在说话
        this.isPlaying = true;
        this.isPaused = !!paused;
      }
    },
    
    // 获取可用的语音列表
    getAvailableVoices() {
      return speechSynthesis.getVoices();
    },
    
    // 设置语音
    setVoice(voice: SpeechSynthesisVoice | null) {
      console.log('尝试设置语音:', voice);
      // 确保传入的语音是有效的
      if (voice && typeof voice === 'object' && 'name' in voice && voice.name) {
        console.log('设置有效语音:', voice.name);
        this.voiceSettings.voice = voice;
        if (this.isPlaying) {
          this.playChapter(this.currentChapter); // 重新播放以应用新设置
        }
        this.saveToLocalStorage();
      } else {
        console.log('清除语音设置');
        this.voiceSettings.voice = null;
        this.saveToLocalStorage();
      }
    },
    
    // 设置语速
    setRate(rate: number) {
      this.voiceSettings.rate = Math.max(0.1, Math.min(10, rate));
      if (this.isPlaying) {
        this.playChapter(this.currentChapter);
      }
      this.saveToLocalStorage();
    },
    
    // 设置音调
    setPitch(pitch: number) {
      this.voiceSettings.pitch = Math.max(0, Math.min(2, pitch));
      if (this.isPlaying) {
        this.playChapter(this.currentChapter);
      }
      this.saveToLocalStorage();
    },
    
    // 设置音量
    setVolume(volume: number) {
      this.voiceSettings.volume = Math.max(0, Math.min(1, volume));
      if (this.isPlaying) {
        this.playChapter(this.currentChapter);
      }
      this.saveToLocalStorage();
    },
    
    // 切换自动播放
    toggleAutoPlay() {
      this.autoPlay = !this.autoPlay;
      console.log('自动播放:', this.autoPlay ? '开启' : '关闭');
      this.saveToLocalStorage();
    },
    
    // 设置自动播放延迟
    setAutoPlayDelay(delay: number) {
      this.autoPlayDelay = Math.max(0, Math.min(10000, delay));
      this.saveToLocalStorage();
    },
    
    // 保存到本地存储
    saveToLocalStorage() {
      try {
        // 保存书籍数据
        if (this.bookTitle && this.chapters.length > 0) {
          localStorage.setItem(STORAGE_KEYS.BOOK_DATA, JSON.stringify({
            title: this.bookTitle,
            chapters: this.chapters,
            timestamp: Date.now()
          }));
        }
        
        // 保存语音设置
        localStorage.setItem(STORAGE_KEYS.VOICE_SETTINGS, JSON.stringify(this.voiceSettings));
        
        // 保存自动播放设置
        localStorage.setItem(STORAGE_KEYS.AUTO_PLAY, JSON.stringify({
          autoPlay: this.autoPlay,
          autoPlayDelay: this.autoPlayDelay
        }));
        
        // 保存当前章节
        localStorage.setItem(STORAGE_KEYS.CURRENT_CHAPTER, this.currentChapter.toString());
        
        console.log('✅ 设置已保存到本地存储');
      } catch (error) {
        console.error('❌ 保存到本地存储失败:', error);
      }
    },
    
    // 从本地存储加载
    loadFromLocalStorage() {
      try {
        // 加载书籍数据
        const bookData = localStorage.getItem(STORAGE_KEYS.BOOK_DATA);
        if (bookData) {
          const parsed = JSON.parse(bookData);
          // 检查数据是否过期（7天）
          if (Date.now() - parsed.timestamp < 7 * 24 * 60 * 60 * 1000) {
            this.bookTitle = parsed.title;
            this.chapters = parsed.chapters;
            console.log('📚 已加载保存的书籍:', this.bookTitle);
          } else {
            console.log('📚 保存的书籍数据已过期，已清除');
            localStorage.removeItem(STORAGE_KEYS.BOOK_DATA);
          }
        }
        
        // 加载语音设置
        const voiceSettings = localStorage.getItem(STORAGE_KEYS.VOICE_SETTINGS);
        if (voiceSettings) {
          this.voiceSettings = { ...this.voiceSettings, ...JSON.parse(voiceSettings) };
          console.log('🎤 已加载语音设置');
        }
        
        // 加载自动播放设置
        const autoPlayData = localStorage.getItem(STORAGE_KEYS.AUTO_PLAY);
        if (autoPlayData) {
          const parsed = JSON.parse(autoPlayData);
          this.autoPlay = parsed.autoPlay;
          this.autoPlayDelay = parsed.autoPlayDelay;
          console.log('🔄 已加载自动播放设置');
        }
        
        // 加载当前章节
        const currentChapter = localStorage.getItem(STORAGE_KEYS.CURRENT_CHAPTER);
        if (currentChapter && this.chapters.length > 0) {
          const chapterIndex = parseInt(currentChapter);
          if (chapterIndex >= 0 && chapterIndex < this.chapters.length) {
            this.currentChapter = chapterIndex;
            console.log('📖 已恢复到章节:', this.currentChapter + 1);
          }
        }
      } catch (error) {
        console.error('❌ 从本地存储加载失败:', error);
      }
    },
    
    // 清除本地存储
    clearLocalStorage() {
      try {
        Object.values(STORAGE_KEYS).forEach(key => localStorage.removeItem(key));
        console.log('🗑️ 本地存储已清除');
      } catch (error) {
        console.error('❌ 清除本地存储失败:', error);
      }
    }
  }
});
